//
//  JCBusinessCardContentView.swift
//  JChat
//
//  Created by JIGUANG on 2017/8/31.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import MTCategory

class JCMessageGiftContentView: UIView, JCMessageContentViewType {

    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }
    
    private func arrtibute(giftName: String, giftCount: Int) -> NSAttributedString {
        
        let markAttribute = NSMutableAttributedString(string: "\(giftCount)")
        let arrtibuteValue: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor : UIColor.text.x1d1a1a,
                                                             NSAttributedString.Key.font : PingFangSCSemiboldFont(24)]
        
        markAttribute.addAttributes(arrtibuteValue, range: NSRange(location: 0, length: "\(giftCount)".count))
        
        let endAttribute = NSMutableAttributedString(string: " 送了\"\(giftName)\"")
        let endarrtibuteValue: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor : UIColor(hex: 0x29282b),
                                                               NSAttributedString.Key.font : PingFangSCMediumFont(12)]
        endAttribute.addAttributes(endarrtibuteValue, range: NSRange(location: 0, length: " 送了\"\(giftName)\"".count))
        
        markAttribute.append(endAttribute)
        
        let xAttribute = NSMutableAttributedString(string: "x ")
        let xarrtibuteValue: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor : UIColor.text.x1d1a1a,
                                                               NSAttributedString.Key.font : PingFangSCSemiboldFont(18)]
        xAttribute.addAttributes(xarrtibuteValue, range: NSRange(location: 0, length: "x ".count))
        
        
        markAttribute.insert(xAttribute, at: 0)
        
        return markAttribute
    
    }
    
    open func apply(_ message: JCMessageType) {
        guard let content = message.content as? JCMessageGiftContent else {
            return
        }
        /*
         * targetType -
         * status - 礼物状态
         *
         */
        _extras = content.extras
        _message = message
        _delegate = content.delegate
        _userName = content.userName
        _appKey = content.appKey
        
        _isSelf = (message.sender?.username == JMSGUser.myInfo().username)
        
        imageView.mtSetImage(_extras?["giftImage"] as? String, nil)
        
        if let giftCount = _extras?["giftNum"] as? Int, let giftName = _extras?["giftName"] as? String {
            tipsLabel.attributedText = arrtibute(giftName: giftName, giftCount: giftCount)
        }
        
        let isSelf: Bool = (message.sender?.username == JMSGUser.myInfo().username)
        
        if isSelf {
            backgroudV.image = UIImage(named: "chat_bubble_send_nor")
            self.bottomView.layer.removeAllSublayers()
            self.bottomView.layer.insertSublayer(self.originLayer, at: 0)
        } else {
            DispatchQueue.main.async {
                self._updateConstraint()
            }
            self.bottomView.layer.removeAllSublayers()
            self.bottomView.layer.insertSublayer(self.replaceLayer, at: 0)
            backgroudV.image = UIImage(named: "chat_bubble_recive_highlighted")
        }
        
        if let serverMsgId = message.jmessage?.serverMessageId {
            if let info: MTGiftInfo = MTGiftInfoDB.shareInstance.quaryData(msgId: serverMsgId).first {
                lineView.isHidden = false
                giftStatusLabel.backgroundColor = .clear
                giftStatusLabel.textColor = UIColor.text.x1d1a1a
                bottomView.isHidden = true
                
                if info.status == .opend {
                    giftStatusLabel.text = "已接受"
                }
                
                if info.status == .invalid {
                    giftStatusLabel.text = "已过期"
                }
            } else if let status: Int = _extras?["status"] as? Int, status == 1 {
                lineView.isHidden = false
                giftStatusLabel.text = "已接受"
                giftStatusLabel.backgroundColor = .clear
                giftStatusLabel.textColor = UIColor.text.x1d1a1a
                
                bottomView.isHidden = true
            } else if let status: Int = _extras?["status"] as? Int, status == 2 {
                lineView.isHidden = false
                giftStatusLabel.text = "已过期"
                giftStatusLabel.backgroundColor = .clear
                giftStatusLabel.textColor = UIColor.text.x1d1a1a
                
                bottomView.isHidden = true
            } else {
                lineView.isHidden = true
                giftStatusLabel.text = "等待拆开"
                giftStatusLabel.textColor = UIColor(hex: 0xffc000)
                bottomView.isHidden = false
            }
        }
    }
    
    lazy var replaceLayer: CAShapeLayer = {
        let width = 230
        let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
        let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: 33), byRoundingCorners: corner, cornerRadii: CGSize(width: 4, height: 4))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = CGRect(x: 0, y: 0, width: width, height: 33)
        maskLayer.path = maskPath.cgPath
        return maskLayer
    }()
    
    lazy var originLayer: CAShapeLayer = {
        let width = 227
        let corner = UIRectCorner(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue)
        let maskPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: 33), byRoundingCorners: corner, cornerRadii: CGSize(width: 4, height: 4))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = CGRect(x: 0, y: 0, width: width, height: 33)
        maskLayer.path = maskPath.cgPath
        return maskLayer
    }()
    
    private func _updateConstraint() {
        imageView.snp.updateConstraints { (make) in
            make.left.equalToSuperview().offset(22)
            make.width.height.equalTo(40)
        }

        tipsLabel.snp.updateConstraints { (make) in
            make.left.equalTo(imageView.snp.right).offset(5)
        }
        
        lineView.snp.updateConstraints { (make) in
            make.right.equalToSuperview().offset(-4)
            make.left.equalToSuperview().offset(14)
        }
        
        bottomView.snp.remakeConstraints { (make) in
            make.right.equalToSuperview().offset(-3)
            make.left.equalToSuperview().offset(14)
            make.top.equalTo(topView.snp.bottom).offset(2)
            make.height.equalTo(31)
        }
    }
    
    private weak var _delegate: JCMessageDelegate?
    
    private var _userName: String?
    private var _appKey: String?
    private var _nickname: String?
    private var _message: JCMessageType!
    private var _user: JMSGUser?
    private var _extras: [String : Any]?
    /// 是否是自己发送的消息
    private var _isSelf: Bool?
    
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: defaultPlaceholderIcon60x60)
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var tipsLabel: UILabel = {
        let tipsLabel = UILabel()
        tipsLabel.font = PingFangSCSemiboldFont(16)
        tipsLabel.textColor = UIColor.text.x1d1a1a
        return tipsLabel
    }()
    
    lazy var backgroudV: UIImageView = {
        let v = UIImageView(image: UIImage(named: "chat_bubble_send_nor"))
        v.layer.masksToBounds = true
        return v
    }()
    
    //UIImage(named: "chat_bubble_send_nor")
    lazy var topView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.clear
        return v
    }()
    
    lazy var bottomView: UIView = {
        let v = UIView()
        v.layer.insertSublayer(originLayer, at: 0)
        return v
    }()
    
    lazy var giftStatusLabel: UILabel = {
        let title: UILabel = UILabel()
        title.font = PingFangSCMediumFont(14)
        title.textAlignment = .center
        return title
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xf6f6f6)
        return v
    }()
    
    private func _commonInit() {
        _tapGesture()
        addSubview(backgroudV)
        addSubview(lineView)
        backgroudV.addSubview(topView)
        
        topView.addSubview(imageView)
        topView.addSubview(tipsLabel)
        
        backgroudV.addSubview(bottomView)
        backgroudV.addSubview(giftStatusLabel)
        
        makeConstraint()
    }
    
    private func makeConstraint() {
        backgroudV.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        topView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(55)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(4)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(2)
            make.top.equalTo(topView.snp.bottom).offset(-1)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(topView.snp.bottom).offset(0)
            make.height.equalTo(31)
        }
        
        imageView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(7)
            make.width.height.equalTo(40)
        }

        tipsLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(imageView.snp.right).offset(5)
        }
        
        giftStatusLabel.snp.makeConstraints { (make) in
            make.edges.equalTo(bottomView)
        }
    }
    
    func _tapGesture() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(_clickCell))
        tap.numberOfTapsRequired = 1
        addGestureRecognizer(tap)
    }
    
    @objc func _clickCell() {
        /// 如果自己点击自己的礼物, 不做处理
        if _isSelf == true {
            return
        }
        //_delegate?.message?(message: _message, user: _user, businessCardName: _userName!, businessCardAppKey: _appKey!)
        _delegate?.tapGiftMessage?(message: _message)
    }

}
